/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
//The MIT License
//
//Copyright (c) 2009 Carl Bystršm
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAim, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

package xin.alum.aim.client.websocket;

import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.SneakyThrows;
import xin.alum.aim.handler.BaseServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import xin.alum.aim.model.Aim;

import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@ChannelHandler.Sharable
public class WebSocketClientHandler extends BaseServerHandler<Object> {

    public static int msgCount = 0;
    private final WebSocketClientHandshaker handshaker;
    public Timer timer = new Timer();
    Channel ch;
    private ChannelPromise handshakeFuture;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                logger.info("收到消息数-{},{}", msgCount, ch.isOpen());
            }
        }, 5000, 3000);
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        handshaker.handshake(ctx.channel());
    }

    @SneakyThrows
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        logger.info("{} 收到消息：WebSocket Client disconnected!", ctx.channel());
        super.channelInactive(ctx);
    }

    @SneakyThrows
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) {
        msgCount++;
        ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            try {
                //这里处理握手返回结果 FullHttpResponse
                handshaker.finishHandshake(ch, (FullHttpResponse) msg);
                logger.info("{} WebSocket Client connected!", ctx.channel());
                handshakeFuture.setSuccess();
            } catch (WebSocketHandshakeException e) {
                logger.info("{} WebSocket Client failed to connect", ctx.channel());
                handshakeFuture.setFailure(e);
            }
            return;
        }

        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;
            throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
        }
        if (msgCount == 1) {
            if (msg instanceof TextWebSocketFrame) {
                final String message = ((TextWebSocketFrame) msg).text();
                ctx.executor().execute(() -> {
                    logger.info("{} 收到消息\n{}", ctx.channel(), message);
                });
            } else if (msg instanceof PongWebSocketFrame) {
                logger.info("{}收到消息：PONG", ctx.channel());
            } else if (msg instanceof CloseWebSocketFrame) {
                logger.info("{}收到消息：WebSocket Closed", ctx.channel());
                ch.close();
            } else if (msg instanceof BinaryWebSocketFrame) {
                ByteBuf buffer = ((BinaryWebSocketFrame) msg).content();
                InputStream inputStream = new ByteBufInputStream(buffer);
                Aim.Packet re = Aim.Packet.parseFrom(inputStream);
                long t = System.currentTimeMillis() - re.getTimestamp();
                logger.info("{} 收到消息用时{},计数{}", ctx.channel(), t, msgCount);
                if (msgCount == 1) {
                    logger.info("{} 收到消息：{}}", ctx.channel(), re.toString());
                }
            } else if (msg instanceof Aim.Packet) {
                logger.info("{} 收到消息：{}}", ctx.channel(), msg);
            }
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (!handshakeFuture.isDone()) {
            handshakeFuture.setFailure(cause);
        }
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (!(evt instanceof IdleStateEvent)) {
            return;
        }

        if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
            ctx.writeAndFlush(new PingWebSocketFrame());
        }
    }


    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().eventLoop().schedule(() -> {
            timer.cancel();
            logger.warn("{}断开重连,", ctx.channel());
            try {
//                WebSocketClient.handler.handshakeFuture().syncUninterruptibly().
                WebSocketClient.connect();
                msgCount = 0;
            } catch (Exception e) {
                logger.error(e);
            }
        }, 1, TimeUnit.SECONDS);
        super.channelUnregistered(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
    }
}
